package com.cskaoyan.service.systemservice;

import com.cskaoyan.bean.systembean.Admin;
import com.cskaoyan.bean.systembean.AdminExample;
import com.cskaoyan.mapper.systemmapper.AdminMapper;
import com.cskaoyan.vo.systemvo.ListVo;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    AdminMapper adminMapper;


    /**
     * @param page  页数
     * @param limit 每页内容数
     * @param sort  排序的根据
     * @param order 正序or倒叙
     * @return 返回vo
     */
    @Override
    public ListVo list(Integer page, Integer limit, String username, String sort, String order) {
        //设置排序规则
        AdminExample adminExample = new AdminExample();
        if (username != null && !"".equals(username)) {
            AdminExample.Criteria criteria = adminExample.createCriteria();
            criteria.andUsernameLike("%" + username + "%");
        }
        adminExample.setOrderByClause(sort + " " + order);
        //得到数据集
        List<Admin> admins = adminMapper.selectByExample(adminExample);

        //将数据塞入vo
        ListVo listVo = new ListVo();
        ArrayList<ListVo.ItemsBean> itemsBeans = new ArrayList<>();

        Iterator<Admin> iterator = admins.iterator();
        while (iterator.hasNext()) {
            Admin admin = iterator.next();
            ListVo.ItemsBean itemsBean = new ListVo.ItemsBean();
            itemsBean.setId(admin.getId());
            itemsBean.setUsername(admin.getUsername());
            itemsBean.setAvatar(admin.getAvatar());
            itemsBean.setRoleIds(admin.getRoleIds());
            itemsBeans.add(itemsBean);
        }

        listVo.setTotal(admins.size());
        //设置分页
        PageHelper.startPage(page, limit);
        listVo.setItems(itemsBeans);


        return listVo;
    }

    /**
     * 添加管理员
     *
     * @param admin
     * @return
     */
    @Override
    public Admin create(Admin admin) {
        int id = adminMapper.insertSelective(admin);
        id = admin.getId();
        Admin admin1 = adminMapper.selectByPrimaryKey(id);

        return admin1;
    }

    /**
     * 更新管理员信息
     *
     * @param admin
     * @return
     */
    @Override
    public Admin update(Admin admin) {
        adminMapper.updateByPrimaryKeySelective(admin);
        Admin admin1 = adminMapper.selectByPrimaryKey(admin.getId());
        return admin1;
    }

    @Override
    public void delete(Admin admin) {
        //物理删除
        adminMapper.deleteByPrimaryKey(admin.getId());


//        //逻辑删除
//        Admin admin1 = new Admin();
//        admin1.setId(admin.getId());
//        admin1.setDeleted(true);
//        adminMapper.updateByPrimaryKeySelective(admin1);
    }


}
